package com.jjs.jcenterdemo;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.white.commonlib.manager.LogManager;

import java.util.Map;

public class WebViewActivity extends AppCompatActivity
{

    WebView webView;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broswer);
        webView = (WebView) findViewById(R.id.webview);
        initConfig();
        getIntentData();
    }

    String url;

    private void getIntentData()
    {
        url = "file:///android_asset/web/index.html";
        if (TextUtils.isEmpty(url))
        {
            finish();
        }
        webView.loadUrl(url);
    }

    private void initConfig()
    {
        webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                /**
                 * 通过判断拦截到的url是否含有pre，来辨别是http请求还是调用android方法的请求
                 */
                String pre = "protocol://android";
                if (!url.contains(pre))
                {
                    //该url是http请求，用webview加载url
                    return false;
                }
                //该url是调用android方法的请求，通过解析url中的参数来执行相应方法
                Map<String, String> map = getParamsMap(url, pre);
                String code = map.get("code");
                String data = map.get("data");
                LogManager.e(data);
                return true;
            }
        });
        webView.setWebChromeClient(new MyChormeClient());
        WebSettings set = webView.getSettings();
        set.setJavaScriptEnabled(true);
//        webView.addJavascriptInterface(new InJavaScriptLocalObj(),"local_obj");
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示

        webView.addJavascriptInterface(new Operate(), "dj");
//        webView.loadUrl("javascript:javaCallJs("+"'"+numebr+"'"+")");
        set.setJavaScriptEnabled(true);
    }

    private Map<String, String> getParamsMap(String url, String pre)
    {
        ArrayMap<String, String> queryStringMap = new ArrayMap<>();
        if (url.contains(pre))
        {
            int index = url.indexOf(pre);
            int end = index + pre.length();
            String queryString = url.substring(end + 1);

            String[] queryStringSplit = queryString.split("&");

            String[] queryStringParam;
            for (String qs : queryStringSplit)
            {
                if (qs.toLowerCase().startsWith("data="))
                {
                    //单独处理data项，避免data内部的&被拆分
                    int dataIndex = queryString.indexOf("data=");
                    String dataValue = queryString.substring(dataIndex + 5);
                    queryStringMap.put("data", dataValue);
                } else
                {
                    queryStringParam = qs.split("=");

                    String value = "";
                    if (queryStringParam.length > 1)
                    {
                        //避免后台有时候不传值,如“key=”这种
                        value = queryStringParam[1];
                    }
                    queryStringMap.put(queryStringParam[0].toLowerCase(), value);
                }
            }
        }
        return queryStringMap;
    }

    class Operate
    {
        @JavascriptInterface
        public void msgBox()
        {
            new AlertDialog.Builder(WebViewActivity.this)
                    .setTitle("对话框")
                    .setMessage("js调安卓原生对话框")
                    .show();
        }
    }

    class MyChormeClient extends WebChromeClient
    {

        @Override
        public void onProgressChanged(WebView view, int newProgress)
        {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String titleStr)
        {
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack())
        {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
